package com.zjj.concurrent.aqs.semaphore;

import java.util.concurrent.Semaphore;

/**
 * @author zhanglei.zjj
 * @description Semaphore简单使用，模拟三个窗口5个人来买票场景
 * @date 2023/5/21 10:49
 */
public class SemaphoreTest {
    public static void main(String[] args) {
        // 声明3个窗口  state:  资源数
        Semaphore windows = new Semaphore(3);

        for (int i = 0; i < 5; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 占用窗口    加锁
                        windows.acquire();
                        System.out.println(Thread.currentThread().getName() + ": 开始买票");
                        //模拟买票流程
                        Thread.sleep(5000);
                        System.out.println(Thread.currentThread().getName() + ": 购票成功");

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        // 释放窗口
                        windows.release();
                    }
                }
            }).start();

        }
    }
}
